{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "22bb4f41-0b48-4165-9b95-1114a9aaa873",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "\n",
    "load_dotenv()\n",
    "\n",
    "# OpenAI API Key\n",
    "OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')\n",
    "OPENAI_API_URL = \"https://api.openai.com/v1/chat/completions\"\n",
    "\n",
    "elastic_user=os.getenv('ES_USER')\n",
    "elastic_password=os.getenv('ES_PASSWORD')\n",
    "elastic_endpoint=os.getenv(\"ES_ENDPOINT\")\n",
    "openai_api_key=os.getenv('OPENAI_API_KEY')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "606b6cec-2f81-406c-9fdb-eedb7b3a18f5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "This image shows a handwritten letter to Santa Claus, presumably written by a child named Maria, who is 8 years old and lives in Rio de Janeiro. The letter is on a torn piece of lined notebook paper, indicating it may have been removed from a spiral-bound notebook.\n",
      "\n",
      "In the letter, Maria politely inquires about Santa's well-being before introducing herself. She then states that she is writing to ask for a Christmas present. She emphasizes that she has been well-behaved throughout the year, mentioning that she has done her homework, helped her parents with chores, and been kind to her friends.\n",
      "\n",
      "Maria lists her Christmas wishes, specifically asking for \"Barbie Dreamhouse Adventures\" and \"My Little Pony.\" These items suggest that Maria enjoys popular children's toys and shows associated with those toys.\n",
      "\n",
      "She closes the letter by acknowledging Santa's busy schedule and expresses hope that he will be able to bring her the requested presents. The letter concludes with a polite thank you and is signed \"With love, Maria,\" showcasing the traditional and respectful format often encouraged in letters to Santa.\n"
     ]
    }
   ],
   "source": [
    "from PIL import Image\n",
    "import requests\n",
    "import numpy as np\n",
    "\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.schema.messages import HumanMessage, SystemMessage\n",
    "\n",
    "image_path = 'https://i.imgur.com/IxC9lgd.png'\n",
    "\n",
    "chat = ChatOpenAI(model=\"gpt-4-vision-preview\", max_tokens=512, openai_api_key=openai_api_key)\n",
    "result = chat.invoke(\n",
    "    [\n",
    "        HumanMessage(\n",
    "            content=[\n",
    "                {\"type\": \"text\", \"text\": \"What is in the picture? Please provide a detailed introduction.\"},\n",
    "                {\n",
    "                    \"type\": \"image_url\",\n",
    "                    \"image_url\": {\n",
    "                        \"url\": image_path,\n",
    "                        \"detail\": \"auto\",\n",
    "                    },\n",
    "                },\n",
    "            ]\n",
    "        )\n",
    "    ]\n",
    ")\n",
    "\n",
    "\n",
    "print(result.content)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "77e721de-3daa-47d2-bb99-c14ec13addaa",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"child_name\": \"Maria\",\n",
      "  \"wishlist\": [\n",
      "    \"Barbie Dreamhouse Adventures\",\n",
      "    \"My Little Pony\"\n",
      "  ]\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "from langchain.prompts import PromptTemplate\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "from langchain.schema import StrOutputParser\n",
    "\n",
    "chain = ChatOpenAI(model=\"gpt-3.5-turbo\", max_tokens=1024)\n",
    "\n",
    "prompt = PromptTemplate.from_template(\n",
    "\"\"\"\n",
    "Extract the list and child's name from the text below and return the data in JSON format using the following name:\n",
    "- \"child_name\", \"wishlist\".\n",
    "\n",
    "{santalist}\n",
    "\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "runnable = prompt | chain | StrOutputParser()\n",
    "\n",
    "letter = result.content\n",
    "wishlist = runnable.invoke({\"santalist\": letter})\n",
    "print(wishlist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "c7dffbd7-7ae5-4ba9-a969-4e7ee5e2016d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"child_name\": \"Maria\",\n",
      "  \"wishlist\": [\n",
      "    \"Barbie Dreamhouse Adventures\",\n",
      "    \"My Little Pony\"\n",
      "  ],\n",
      "  \"weight\": 0.5\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "chain = ChatOpenAI(model=\"gpt-3.5-turbo\", max_tokens=1024)\n",
    "\n",
    "prompt = PromptTemplate.from_template(\n",
    "\"\"\"\n",
    "\n",
    "{santalist_json}\n",
    "\n",
    "From the JSON above, include a new attribute in the JSON called 'weight',\n",
    "which will calculate the total estimated weight of each item in the list in kilograms.\n",
    "\n",
    "You will first need to estimate the weight of each item individually.\n",
    "After that, sum these values to obtain the total weight.\n",
    "Extract only the numerical value.\n",
    "\n",
    "\"\"\"\n",
    ")\n",
    "\n",
    "runnable = prompt | chain | StrOutputParser()\n",
    "\n",
    "new_wishlist = runnable.invoke({\"santalist_json\": wishlist})\n",
    "print(new_wishlist)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d77b2300-7b40-4d5b-8380-dbd9f694f038",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'_index': 'santa_claus_list', '_id': 'rHoY8owB6xtD7DLUdxmY', '_version': 1, 'result': 'created', '_shards': {'total': 2, 'successful': 1, 'failed': 0}, '_seq_no': 0, '_primary_term': 1}\n"
     ]
    }
   ],
   "source": [
    "from elasticsearch import Elasticsearch\n",
    "import json\n",
    "\n",
    "url = f\"https://{elastic_user}:{elastic_password}@{elastic_endpoint}:9200\"\n",
    "es = Elasticsearch(url, ca_certs = \"./http_ca.crt\", verify_certs = True)\n",
    "\n",
    "es.info() # should return cluster info\n",
    "\n",
    "# Parse the JSON string\n",
    "json_string = new_wishlist\n",
    "data = json.loads(json_string)\n",
    "\n",
    "# Index name\n",
    "index_name = \"santa_claus_list\"\n",
    "\n",
    "# Index the document\n",
    "response = es.index(index=index_name, document=data)\n",
    "\n",
    "# Print the response from Elasticsearch\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61b8abeb-c0d6-42f9-8b4f-384eabb3edcf",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python_3.11",
   "language": "python",
   "name": "python_3.11"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
